package com.zxjbyte.yiyi.module.plugin.sse.controller;

import com.zxjbyte.yiyi.framework.common.constant.Constant;
import com.zxjbyte.yiyi.framework.common.domain.api.R;
import com.zxjbyte.yiyi.module.plugin.sse.domain.request.MessageRequest;
import com.zxjbyte.yiyi.module.plugin.sse.service.SseEmitterService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * @Author zhangxingjia
 * @Date 2024/6/24 17:47
 * @Version: 1.0
 */
@Tag(name = "SSE通信控制器")
@RestController
@RequestMapping(value = Constant.BASE_PATH_PLUGIN + "/sse")
public class SseEmitterController {

    @Resource
    private SseEmitterService sseEmitterService;

    @Operation(summary = "创建sse连接")
    @GetMapping("/connect")
    public SseEmitter createConnect(@RequestParam(required = false) String clientId,
                                    @RequestParam(required = false, defaultValue = "true") Boolean openHeartBeat){
        return sseEmitterService.createConnect(clientId, openHeartBeat);
    }

    @Operation(summary = "关闭sse连接")
    @GetMapping("/close_connect")
    public R<?> closeConnect(@RequestParam(required = false) String clientId){
        sseEmitterService.closeConnect(clientId);
        return R.ok();
    }

    @Operation(summary = "广播")
    @PostMapping("/broadcast")
    public R<?> broadcast(@Valid @RequestBody MessageRequest request){
        sseEmitterService.broadcast(request.getClientId(), request.getMessage());
        return R.ok();
    }

    @Operation(summary = "发送指定用户消息")
    @PostMapping("/sendOne")
    public R<?> sendOne(@Valid @RequestBody MessageRequest request){
        sseEmitterService.sendOne(request.getClientId(), request.getMessage());
        return R.ok();
    }
}
